<?php

namespace plugin\ycMassage\app\admin\controller;

use app\common\builder\FormBuilder;
use app\common\builder\ListBuilder;
use app\common\service\UploadService;
use app\common\trait\SettingsTrait;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageAppointmentService;
use plugin\ycMassage\app\model\MassageOrders;
use plugin\ycMassage\app\model\MassageOrdersAddress;
use plugin\ycMassage\app\model\MassageOrdersSub;
use plugin\ycMassage\app\model\MassageOrdersTransferring;
use plugin\ycMassage\app\model\MassageUser;
use plugin\ycMassage\utils\enum\ActionIdentity;
use plugin\ycMassage\utils\enum\Examine;
use plugin\ycMassage\utils\enum\NoticeType;
use plugin\ycMassage\utils\enum\OrdersState;
use plugin\ycMassage\utils\enum\OrdersType;
use plugin\ycMassage\utils\enum\PayType;
use plugin\ycMassage\utils\enum\ServiceState;
use plugin\ycMassage\utils\notice\Notice;
use think\facade\Db;
use think\Request;

class OrdersController extends BaseController
{
    use SettingsTrait;

    /**
     * 应用ID（null则获取系统配置）
     * @var int|null
     * @author 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    protected $saas_appid = null;

    /**
     * 构造函数
     * @return void
     * @author 贵州猿创科技有限公司
     * @copyright 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    public function initialize()
    {
        parent::initialize();
        $this->saas_appid = $this->request->saas_appid;
    }
    public function indexGetTable(Request $request)
    {
        $limit   = $request->get('limit', 20);
        $builder = new ListBuilder;
        $builder->addActionOptions('操作', [
            'width' => 160
        ]);
        $builder->checkboxConfig();
        $builder->pageConfig([
            'pageSize' => $limit
        ]);
        $builder->exportConfig([
            'api' => $this->pluginPrefix . '/admin/Orders/index',
        ]);
        $builder->addScreen('trade', 'input', '订单号');
        $builder->addScreen('name', 'input', '下单人');
        $builder->addScreen('mobile', 'input', '下单手机号');
        $builder->addScreen('technician', 'input', '技师');
        $builder->addScreen('state', 'select', '状态', [
            'options' => OrdersState::getOptions()
        ]);
        $builder->addScreen('start_time', 'input', '开始时间', [
            'type' => 'date'
        ]);
        $builder->addScreen('end_time', 'input', '结束时间', [
            'type' => 'date'
        ]);
        $builder->addBottomButton('deleteAll', '删除', [
            'api'    => $this->pluginPrefix . '/admin/Orders/deleteAll',
            'type'      => 'confirm',
            'method' => 'delete',
        ], [
            'type' => 'danger',
            'title'   => '温馨提示',
            'content' => '是否确认删除所选数据',
        ], [
            'type' => 'danger',
        ]);
        $builder->addRightButton('details', '详情', [
            'api'    => $this->pluginPrefix . '/admin/Orders/details',
            'path' => '/Orders/details',
            'type'      => 'modal'
        ], [
            'title'   => '订单详情',
            'customStyle' => [
                'width' => '1140px',
                'minHeight' => '800px'
            ]
        ], [
            'type' => 'primary',
            'link' => true
        ]);
        $builder->addRightButton('handle', '转单', [
            'api'    => $this->pluginPrefix . '/admin/OrdersTransferring/handle',
            'path' => '/OrdersTransferring/handle',
            'type'      => 'modal',
            'params' => [
                'field' => 'state',
                'where' => '=',
                'value' => OrdersState::TRANSFERRING_ORDERS['value']
            ],
            'aliasParams' => [
                'id' => 'orders_id'
            ],
        ], [
            'customStyle' => [
                'width' => '1140px',
                'minHeight' => '800px'
            ]
        ], [
            'type' => 'success',
            'link' => true
        ]);
        $builder->addRightButton('complete', '完成', [
            'api'    => $this->pluginPrefix . '/admin/Orders/complete',
            'type'      => 'confirm',
            'method' => 'post',
            'params' => [
                'field' => 'state',
                'where' => 'in',
                'value' => [OrdersState::NOT_PAY['value'], OrdersState::PAY['value']]
            ]
        ], [
            'title'   => '温馨提示',
            'content' => '是否确认完成订单',
        ], [
            'type' => 'success',
            'link' => true
        ]);
        $builder->addRightButton('delete', '删除', [
            'api'    => $this->pluginPrefix . '/admin/Orders/delete',
            'type'      => 'confirm',
            'method' => 'delete',
            'params' => [
                'field' => 'state',
                'where' => '=',
                'value' => OrdersState::CANCEL['value']
            ]
        ], [
            'title'   => '温馨提示',
            'content' => '是否确认删除该数据',
        ], [
            'type' => 'danger',
            'link' => true
        ]);
        $builder->addColumn('id', '序号', [
            'width' => 90,
            'type' => 'checkbox'
        ])
            ->addColumn('title', '服务项目详情', [
                'minWidth' => 200,
            ])
            ->addColumn('name', '下单人', [
                'width' => 160,
            ])
            ->addColumn('mobile', '下单手机号', [
                'width' => 160,
            ])
            ->addColumn('technician_nickname', '技师', [
                'width' => 160,
            ])
            ->addColumn('origin_price', '原价', [
                'width' => 100,
            ])
            ->addColumn('price', '实付', [
                'width' => 100,
            ])
            ->addColumn('basic_price', '服务价', [
                'width' => 100,
            ])
            ->addColumn('overtime_price', '加钟价', [
                'width' => 100,
            ])
            ->addColumn('travel_price', '出行费', [
                'width' => 100,
            ])
            ->addColumn('material_price', '材料费', [
                'width' => 100,
            ])
            ->addColumn('coupon_money', '优惠', [
                'width' => 100,
            ])
            ->addColumn('num', '服务数量', [
                'width' => 100,
            ])
            ->addColumn('trade', '订单号', [
                'minWidth' => 200,
            ])
            ->addColumnEle('pay_type', '支付方式', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => PayType::dictOptions(),
                ],
            ])
            ->addColumn('pay_time', '支付时间', [
                'width' => 160,
            ])
            ->addColumnEle('state', '状态', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => OrdersState::dictOptions(),
                    'style' => OrdersState::dictOptions('style'),
                ],
            ])
            ->addColumn('remark', '备注', [
                'width' => 160,
            ])
            ->addColumn('create_time', '下单时间', [
                'width' => 160,
            ]);
        return $this->successRes($builder->create());
    }
    public function index(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $where = [
            ['o.saas_appid', '=', $request->saas_appid]
        ];
        $trade = $request->get('trade');
        if ($trade) {
            $where[] = ['o.trade', 'like', '%' . $trade . '%'];
        }
        $uid = $request->get('uid');
        if ($uid) {
            $where[] = ['o.uid', '=', $uid];
        }
        $state = $request->get('state');
        if ($state !== null) {
            $where[] = ['o.state', '=', $state];
        }
        $start_time = $request->get('start_time');
        if ($start_time) {
            $where[] = ['o.create_time', '>=', $start_time . ' 00:00:00'];
        }
        $end_time = $request->get('end_time');
        if ($end_time) {
            $where[] = ['o.create_time', '<=', $end_time . ' 23:59:59'];
        }
        $type = $request->get('type');
        if ($type) {
            $where[] = ['o.orders_type', '=', $type];
        }
        $is_channels = $request->get('is_channels');
        if ($is_channels) {
            $where[] = ['o.channels_id', 'NOT NULL', ''];
        }
        $filed = [
            'o.*',
        ];
        $MassageOrdersObj = MassageOrders::alias('o')->where($where);
        switch ($type) {
            case OrdersType::RESERVATION['value']:
            case OrdersType::OVERTIME['value']:
                $filed[] = 'address.name,address.mobile';
                $filed[] = 'ut.nickname as technician_nickname';
                $technician = $request->get('technician');
                if ($technician) {
                    $where[] = ['t.name|t.mobile', 'like', "%{$technician}%"];
                    $MassageOrdersObj->join('MassageUserTechnician t', 't.uid=o.alias_id');
                }
                $MassageOrdersObj->join('MassageUser ut', 'ut.id=o.alias_id');
                $name = $request->get('name');
                if ($name) {
                    $where[] = ['address.name', 'like', "%{$name}%"];
                }
                $mobile = $request->get('mobile');
                if ($mobile) {
                    $where[] = ['address.mobile', 'like', "%{$mobile}%"];
                }
                $MassageOrdersObj->join('MassageOrdersAddress address', 'address.orders_id = o.id','LEFT');
                break;
            default:
                break;
        }
        $data = $MassageOrdersObj->order('o.id desc')
            ->field($filed)
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->each(function ($item) {
                if ($item->technician_nickname) {
                    $item->technician_nickname = base64_decode($item->technician_nickname);
                }
            });
        return $this->successRes($data);
    }
    public function overtime(Request $request)
    {
        return $this->index($request);
    }
    public function overtimeGetTable(Request $request)
    {
        return $this->indexGetTable($request);
    }
    public function delete(Request $request)
    {
        $id = $request->post('id');
        Db::startTrans();
        try {
            $MassageOrders = MassageOrders::where(['id' => $id, 'saas_appid' => $request->saas_appid, 'state' => OrdersState::CANCEL['value']])->find();
            $MassageOrders->delete();
            Db::commit();
            return $this->success('删除成功');
        } catch (\Throwable $th) {
            Db::rollback();
            return $this->fail($th->getMessage());
        }
    }
    public function deleteAll(Request $request)
    {
        $ids = $request->post('id');
        Db::startTrans();
        try {
            $MassageOrders = MassageOrders::where(['saas_appid' => $request->saas_appid, 'state' => OrdersState::CANCEL['value']])->whereIn('id', $ids)->select();
            foreach ($MassageOrders as $item) {
                $item->delete();
            }
            Db::commit();
            return $this->success('删除成功');
        } catch (\Throwable $th) {
            Db::rollback();
            return $this->fail($th->getMessage());
        }
    }
    public function complete(Request $request)
    {
        $id = $request->post('id');
        try {
            $MassageOrders = MassageOrders::where(['id' => $id, 'saas_appid' => $request->saas_appid])
                ->whereIn('state', [OrdersState::NOT_PAY['value'], OrdersState::PAY['value']])->find();
            if (!$MassageOrders->pay_type) {
                $MassageOrders->pay_type = PayType::ARTIFICIAL['value'];
                $MassageOrders->pay_time = date('Y-m-d H:i:s');
            }
            $MassageOrders->save();
            MassageOrders::complete($MassageOrders->trade);
            return $this->success('完成成功');
        } catch (\Throwable $th) {
            return $this->fail($th->getMessage());
        }
    }
    public function details(Request $request)
    {
        $id = $request->get('id');
        $MassageOrders = MassageOrders::where(['id' => $id, 'saas_appid' => $request->saas_appid])->find();
        if (!$MassageOrders) {
            return $this->fail('数据不存在');
        }
        $MassageUserT = MassageUser::alias('u')->where(['u.id' => $MassageOrders->alias_id])
            ->join('MassageUserWechat uw', 'uw.uid=u.id', 'left')
            ->field('u.id,u.nickname,u.headimg,u.mobile,u.realname,uw.openid')
            ->find();
        $MassageOrdersAddress = MassageOrdersAddress::where(['orders_id' => $MassageOrders->id])->find();
        $MassageAppointmentService = MassageAppointmentService::where(['orders_id' => $MassageOrders->id])->order('state desc')->find();
        if ($request->method() === 'POST') {
            Db::startTrans();
            try {
                $MassageAppointmentService = MassageAppointmentService::where(['orders_id' => $MassageOrders->id])->select();
                if ($MassageAppointmentService->isEmpty()) {
                    throw new \Exception('订单无服务');
                }
                $state = null;
                foreach ($MassageAppointmentService as $item) {
                    if (!in_array($item->state, [ServiceState::WAIT_START['value'], ServiceState::TRAVELING['value'], ServiceState::ARRIVAL['value']])) {
                        throw new \Exception('订单一开始服务不可转单');
                    }
                    $state = $item->state;
                    $item->state = OrdersState::TRANSFERRING_ORDERS['value'];
                    $item->save();
                }
                $MassageOrdersTransferring = new MassageOrdersTransferring();
                $MassageOrdersTransferring->saas_appid = $request->saas_appid;
                $MassageOrdersTransferring->orders_id = $MassageOrders->id;
                $MassageOrdersTransferring->technician_id = $MassageOrders->alias_id;
                $MassageOrdersTransferring->orders_state = $MassageOrders->state;
                $MassageOrdersTransferring->service_state = $state;
                $MassageOrdersTransferring->use_role = ActionIdentity::TECHNICIAN['value'];
                $MassageOrdersTransferring->transferring_message = $request->post('transferring_message');
                $MassageOrdersTransferring->examine = Examine::WAIT['value'];
                $MassageOrdersTransferring->save();
                $MassageOrders->state = OrdersState::TRANSFERRING_ORDERS['value'];
                $MassageOrders->save();
                Db::commit();
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
            return $this->success('转单申请已提交，请管理员审核');
        }
        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addDivider('当前服务技师和客户');
        $builder->addComponent('headimgT', 'el-avatar', '技师头像', '', [
            'col'           => 4,
            'props'         => [
                'size'     => 50,
                'shape' => 'square',
                'src'      => $MassageUserT->headimg,
            ],
        ]);
        $builder->addComponent('nicknameT', 'info', '技师昵称', $MassageUserT->nickname, [
            'col'           => 4,
            'props'         => []
        ]);
        $builder->addComponent('realnameT', 'info', '技师姓名', $MassageUserT->realname, [
            'col'           => 4,
            'props'         => []
        ]);
        if($MassageOrdersAddress){
            $builder->addComponent('realname', 'info', '客户', $MassageOrdersAddress->name, [
                'col'           => 4,
                'props'         => []
            ]);
            $builder->addComponent('mobile', 'info', '客户手机号', $MassageOrdersAddress->mobile, [
                'col'           => 4,
                'props'         => []
            ]);
            $address = "{$MassageOrdersAddress->province}{$MassageOrdersAddress->city}{$MassageOrdersAddress->area}{$MassageOrdersAddress->street}{$MassageOrdersAddress->address_detail}";
            $builder->addComponent('address', 'info', '客户地址', $address, [
                'col'           => 24,
                'props'         => []
            ]);
        }
        if($MassageAppointmentService){
            $builder->addDivider('服务');
            $TechnicianState = [
                'type' => 'error',
                'text' => ServiceState::getText($MassageAppointmentService->state)['text']
            ];
            $builder->addComponent('TechnicianState', 'el-tag', '服务状态', '', [
                'col'           => 6,
                'props'         => [
                    'type'      => $TechnicianState['type']
                ],
                'children'      => [
                    $TechnicianState['text']
                ]
            ]);
            $builder->addComponent('price', 'el-tag', '订单金额', '', [
                'col'           => 6,
                'props'         => [
                    'type'      => 'success'
                ],
                'children'      => [
                    "￥{$MassageOrders->price}"
                ]
            ]);
            $builder->addComponent('travel_price', 'el-tag', '路费', '', [
                'col'           => 6,
                'props'         => [
                    'type'      => 'success'
                ],
                'children'      => [
                    "￥{$MassageOrders->travel_price}"
                ]
            ]);
            $builder->addComponent('start_time', 'info', '预约时间', $MassageAppointmentService->start_time, [
                'col'           => 6
            ]);
        }
        $builder->addDivider('项目');
        $MassageOrdersSub = MassageOrdersSub::alias('os')->where(['os.orders_id' => $MassageOrders->id])
            ->join('MassageService s', 's.id = os.service_id')
            ->field('os.*,s.title,s.thumb')
            ->select()->each(function ($item) {
                $item->thumb = UploadService::url($item->thumb);
            });
        foreach ($MassageOrdersSub as $item) {
            $builder->addComponent('url' . $item->id, 'el-avatar', '封面', '', [
                'col'           => 4,
                'props'         => [
                    'size'     => 50,
                    'shape' => 'square',
                    'src'      => $item->thumb,
                ],
            ]);
            $builder->addComponent('title' . $item->id, 'info', '服务项目', "{$item->title} x {$item->num}", [
                'col'           => 14,
                'props'         => []
            ]);
            $builder->addComponent('price' . $item->id, 'el-tag', '金额', '', [
                'col'           => 6,
                'props'         => [
                    'type'      => 'success'
                ],
                'children'      => [
                    "￥{$item->price}"
                ]
            ]);
        }
        try {
            $MassageAppointmentService = MassageAppointmentService::where(['orders_id' => $MassageOrders->id])->select();
            if ($MassageAppointmentService->isEmpty()) {
                throw new \Exception('订单无服务');
            }
            foreach ($MassageAppointmentService as $item) {
                if (!in_array($item->state, [ServiceState::WAIT_START['value'], ServiceState::TRAVELING['value'], ServiceState::ARRIVAL['value']])) {
                    throw new \Exception('订单开始服务不可转单');
                }
            }
            $builder->addDivider('转单');
            $builder->addRow('is_transferring', 'radio', '审核', 0, [
                'col'                   => [
                    'span'              => 24
                ],
                'options'       => [
                    [
                        'label'     => '无',
                        'value'     => 0
                    ],
                    [
                        'label'     => '开启转单',
                        'value'     => 1
                    ]
                ]
            ]);
            $builder->addRow('transferring_message', 'textarea', '转单原因', '', [
                'col'                   => 24,
                'props'                 => [
                    'placeholder'       => '请输入转单原因'
                ]
            ]);
        } catch (\Throwable $th) {
            $builder->setConf('submitBtn', []);
        }
        # 生成表单规则
        $data = $builder->create();
        return $this->successRes($data);
    }
}
